//
//  UIImage+Category.m
//  XHRuntimeDemo
//
//  Created by craneteng on 16/4/18.
//  Copyright © 2016年 XHTeng. All rights reserved.
//

#import "UIImage+Category.h"
#import <objc/runtime.h>
#import <objc/message.h>

@implementation UIImage (Category)

+ (void)load {
    // 获取两个类的类方法
    SEL originSelector = @selector(imageNamed:);
    SEL swizzlSelector = @selector(xh_imageNamed:);
    
    Method originMethod = class_getClassMethod([UIImage class], originSelector);
    Method swizzleMethod = class_getClassMethod([UIImage class], swizzlSelector);

    //判断方法是否存在，存在：didAddMethod为NO，不存在didAddMethod为YES
    BOOL didAddMethod = class_addMethod([UIImage class], @selector(imageNamed:), method_getImplementation(swizzleMethod), method_getTypeEncoding(swizzleMethod));
    if (didAddMethod) {
        class_replaceMethod([UIImage class], @selector(xh_imageNamed:), method_getImplementation(originMethod), method_getTypeEncoding(originMethod));
    }else{
        // 开始交换方法实现
        method_exchangeImplementations(originMethod, swizzleMethod);
     }
}

+ (UIImage *)xh_imageNamed:(NSString *)name {
    double version = [[UIDevice currentDevice].systemVersion doubleValue];
    if (version >= 7.0) {
        // 如果系统版本是7.0以上，使用另外一套文件名结尾是‘_os7’的扁平化图片
        name = [name stringByAppendingString:@"_os7"];
    }
    return [UIImage xh_imageNamed:name];
}

//+(void)zhSwizzleWithClass:(Class)processedClass originalSelector:(SEL)originSelector swizzleSelector:(SEL)swizzlSelector{
//    Method originMethod = class_getInstanceMethod(processedClass, originSelector);
//    Method swizzleMethod = class_getInstanceMethod(processedClass, swizzlSelector);
//
//    BOOL didAddMethod = class_addMethod(processedClass, originSelector, method_getImplementation(swizzleMethod), method_getTypeEncoding(swizzleMethod));
//    if (didAddMethod) {
//        class_replaceMethod(processedClass, swizzlSelector, method_getImplementation(originMethod), method_getTypeEncoding(originMethod));
//    }else{
//        method_exchangeImplementations(originMethod, swizzleMethod);
//     }
//}
@end
